//
//  FPTopViewController.m
//  FilmParadise
//
//  Created by lanou3g on 15/7/13.
//  Copyright (c) 2015年 DLYgroup. All rights reserved.
//

#import "FPTopViewController.h"
#import "FPTopClassViewCell.h"
#import "FPTopListViewCell.h"
#import "FPNewsHeaderView.h"
#import "FPRankViewController.h"
#import "FPHeaderModel.h"
#import "FPTopModel.h"
#import "FPActorViewController.h"
#import "FPHeadAanimation.h"
#import "FPTopClass.h"
#import "FPGlobalViewController.h"
#define kTopListURL @"http://api.m.mtime.cn/TopList/TopListOfAll.api?pageIndex=1"
#define kTopClassURl @"http://api.m.mtime.cn/TopList/TopListFixedNew.api"
@interface FPTopViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)FPNewsHeaderView *headerView;
@property(nonatomic,strong)UITableView *tableView;
//装载list模型的数组
@property(nonatomic,strong)NSMutableArray *topListArray;
/**装在顶部数组*/
@property(nonatomic,strong)NSMutableArray *topArray;
@property(nonatomic,assign)NSInteger pageIndex;
/**装在第一行cell数组*/
@property(nonatomic,strong)NSMutableArray *topClassArray;

@end

@implementation FPTopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 self.view.frame = CGRectMake(2*kScreenWidth, 0, kScreenWidth, kScreenHeight);
    [self creatTableView];
  //解析headView数据
    [self.tableView addGifHeaderWithRefreshingTarget:self refreshingAction:@selector(TopRefreshAction)];
    [self.tableView.header beginRefreshing];
    [self pullUpLoadMore];
    [self anasisysFirstCellData:kTopClassURl];
}
//下拉刷新
- (void)TopRefreshAction
{
    NSMutableArray *imageArray = [[NSMutableArray alloc]init];
    for (int i = 2; i< 10; i ++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"catRefresh－%d（被拖移）.tiff",i]];
        [imageArray addObject:image];
    }
    [self.tableView.gifHeader setImages:imageArray forState: MJRefreshHeaderStateIdle];
    [self.tableView.gifHeader setImages:imageArray forState:MJRefreshHeaderStatePulling];
    [self.tableView.gifHeader setImages:imageArray forState:MJRefreshHeaderStateRefreshing];
    [self analysisHeaderViewData];
    [self analysisTopListData];
    
    [FPHeadAanimation analysisHA:self.tableView];
}
#pragma mark===========上拉加载更多
- (void)pullUpLoadMore
{
    
    __block typeof(self)blockSelf = self;
   [self.tableView addGifFooterWithRefreshingBlock:^{
       [blockSelf pullUpAnalysis];
   }];
    NSMutableArray *imageArray = [[NSMutableArray alloc]init];
    for (int i = 2; i< 10; i ++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"catRefresh－%d（被拖移）.tiff",i]];
        [imageArray addObject:image];
    }
    [self.tableView.gifFooter setRefreshingImages:imageArray];
    self.tableView.footer.stateHidden = YES;

    
}

- (void)pullUpAnalysis
{
    self.pageIndex += 1;
        NSString *string = [NSString stringWithFormat:@"http://api.m.mtime.cn/TopList/TopListOfAll.api?pageIndex=%ld",self.pageIndex];
    [LORequestManger GET:string success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        NSArray *listArray = dic[@"topLists"];
        for (NSDictionary *listDic in listArray) {
            FPTopModel *model = [FPTopModel fpTopModelSetValueWithDictionary:listDic];
            model.topListId = listDic[@"id"];
            [self.topListArray addObject:model];
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"网络请失败");
    }];

}
//创建TableView
- (void)creatTableView
{
    UIView *view = [[UIView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:view];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,64, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    self.headerView = [[FPNewsHeaderView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kImageH(150) + kImageH(30))];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickTopHeaderImage)];
    [self.headerView.picImageView addGestureRecognizer:tap];
    [self.headerView.introButton addTarget:self action:@selector(clickTopHeaderImage) forControlEvents:UIControlEventTouchUpInside];

    self.tableView.tableHeaderView = _headerView ;

}

- (void)clickTopHeaderImage
{
    FPHeaderModel *model = self.topArray[0];
    if ([model.type integerValue] == 1 ||[model.type integerValue]== 0) {
        FPRankViewController *rankVc = [[FPRankViewController alloc]init];
        rankVc.topListURL = [NSString stringWithFormat:@"http://api.m.mtime.cn/TopList/TopListDetails.api?pageIndex=1&topListId=%@",model.IDStr];
      
        [self.navigationController pushViewController:rankVc animated:YES];
    }
    else
    {
        FPActorViewController *actorVc = [[FPActorViewController alloc]init];
     
        actorVc.actorUrl = [NSString stringWithFormat:@"http://api.m.mtime.cn/TopList/TopListDetails.api?pageIndex=1&topListId=%@",model.IDStr];
        [self.navigationController pushViewController:actorVc animated:YES];
 
    }
}
//网络判断
- (void)judgeNet
{
    if (![[FPNetWork shareInstance]rechability])
    {
        UIAlertView *aler = [[UIAlertView alloc]initWithTitle:nil message:@"无网络" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [aler show];
        return;
    }
}
    
#pragma mark=======================解析头部数据
- (void)analysisHeaderViewData
{
    [self judgeNet];
    self.topArray  = [NSMutableArray array];
    [LORequestManger GET:kHeaderURL success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        NSDictionary *topDic = dic[@"topList"];
        FPHeaderModel *topHeaerModel = [FPHeaderModel fpNewsViewModeltSetValueWithDictionary:topDic];
        topHeaerModel.IDStr = topDic[@"id"];
        [self.topArray addObject:topHeaerModel];
        if ([topHeaerModel.type integerValue]==1)
        {
            self.headerView.rightImageView.hidden = YES;
        }
        else
        {
            self.headerView.rightImageView.hidden = NO;
        }
        [self.headerView.picImageView sd_setImageWithURL:[NSURL URLWithString:topHeaerModel.imageUrl] placeholderImage:nil completed:nil];
        [self.headerView.introButton setTitle:topHeaerModel.title forState:UIControlStateNormal];
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"请求数据失败");
    }];
    
}
#pragma mark======================解析topList数据
-(NSMutableArray *)topListArray
{
    if (!_topListArray) {
        _topListArray = [[NSMutableArray alloc]init];
    }
    return _topListArray;
}
- (void)analysisTopListData
{
    self.pageIndex = 1;
    NSString *string = [NSString stringWithFormat:@"http://api.m.mtime.cn/TopList/TopListOfAll.api?pageIndex=%ld",self.pageIndex];
    [self judgeNet];
    [LORequestManger GET:string success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        NSArray *listArray = dic[@"topLists"];
        for (NSDictionary *listDic in listArray) {
            FPTopModel *model = [FPTopModel fpTopModelSetValueWithDictionary:listDic];
            model.topListId = listDic[@"id"];
            [self.topListArray addObject:model];
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"网络请失败");
    }];
}
#pragma mark ====================analysissun100
- (NSMutableArray *)topClassArray
{
    if (!_topClassArray) {
        _topClassArray = [NSMutableArray array];
    }
    return _topClassArray;
}
- (void)anasisysFirstCellData:(NSString *)string
{
    [LORequestManger GET:string success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
     
        NSArray *listArray = dic[@"topList"];
        
        for (NSDictionary *listDic in listArray) {
            FPTopClass *model = [FPTopClass fpTopClassWithDictionary:listDic];
            [self.topClassArray addObject:model];
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"网络请失败");
    }];

}
#pragma mark=======================实现tableview的代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)return 1;
    return self.topListArray.count;
}
//返回cell的方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString *cellIndentifier = @"TopCell";
        [tableView registerClass:[FPTopClassViewCell class] forCellReuseIdentifier:cellIndentifier];
    
        FPTopClassViewCell *cell  = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
        UITapGestureRecognizer *tapleft = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapView:)];
        cell.leftImageView.tag = 600;
        cell.centreImageView.tag = 601;

        cell.rightImageView.tag = 602;

        
        [cell.leftImageView addGestureRecognizer:tapleft];
         UITapGestureRecognizer *centreTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapView:)];
        [cell.centreImageView addGestureRecognizer:centreTap];
        UITapGestureRecognizer *rightTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapView:)];
        [cell.rightImageView addGestureRecognizer:rightTap];
        [cell cellForModel:self.topClassArray];
      
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else
    {
        static NSString *cellIndentifier = @"ListCell";
        [tableView registerClass:[FPTopListViewCell class] forCellReuseIdentifier:cellIndentifier];
        FPTopListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
        FPTopModel *TopListModel = self.topListArray[indexPath.row];
        [cell adjustSubviewsWithContent:TopListModel];
        return cell;
    }

}

#pragma mark =============点击图片触发事件
- (void)tapView:(UIGestureRecognizer *)sender
{
    FPRankViewController *rankVc = [[FPRankViewController alloc]init];
    UIView *tapView = sender.view;
    tapView.backgroundColor = [UIColor greenColor];
    NSString *string = @"http://api.m.mtime.cn/TopList/TopListDetailsByRecommend.api?pageIndex=1&pageSubAreaID=";
    if (tapView.tag == 600)
    {
        

        FPTopClass *model = self.topClassArray[0];
        rankVc.topListURL = [string stringByAppendingString:model.pageSubAreaId];
        [self.navigationController pushViewController:rankVc animated:YES];
    }
    else if(tapView.tag == 601)
    {
            FPTopClass *model = self.topClassArray[1];
        rankVc.topListURL = [string stringByAppendingString:model.pageSubAreaId];
        [self.navigationController pushViewController:rankVc animated:YES];
    }
    else
    {
        FPGlobalViewController *gloabVc = [[FPGlobalViewController alloc]init];
//        FPTopClass *model = self.topClassArray[2];
//        rankVc.topListURL = [string stringByAppendingString:model.pageSubAreaId];
        [self.navigationController pushViewController:gloabVc animated:YES];

    }
}
//cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
         return kScreenWidth/3;
    }
    else
    {
        FPTopModel *TopListModel = self.topListArray[indexPath.row];
        return [FPTopListViewCell heightForCell:TopListModel];
    }
}
#pragma mark ==================点击cell触发事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  
  
     FPTopModel *TopListModel = self.topListArray[indexPath.row];
    if (indexPath.section == 0)
    {
        
    }
    else
    {
        if ([TopListModel.type integerValue] == 0 ||[TopListModel.type integerValue] ==1)
        {
        FPRankViewController *rankVc = [[FPRankViewController alloc]init];
        FPTopModel *TopListModel = self.topListArray[indexPath.row];
        rankVc.topListURL = [NSString stringWithFormat:@"http://api.m.mtime.cn/TopList/TopListDetails.api?pageIndex=1&topListId=%@",TopListModel.topListId];
        NSLog(@"fgyrtyhrthtjhg8888%@",rankVc.topListURL);
            
        [self.navigationController pushViewController:rankVc animated:YES];
        }
        else
        {
            FPActorViewController *actorVc = [[FPActorViewController alloc]init];
            FPTopModel *TopListModel = self.topListArray[indexPath.row];
            actorVc.actorUrl = [NSString stringWithFormat:@"http://api.m.mtime.cn/TopList/TopListDetails.api?pageIndex=1&topListId=%@",TopListModel.topListId];
         //   NSLog(@"==========%@",actorVc.actorUrl);
            [self.navigationController pushViewController:actorVc animated:YES];
        }

      }
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"cgClear"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.backgroundColor = [UIColor purpleColor];
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth , 20)];
    statusBarView.backgroundColor = [UIColor purpleColor];
    [self.view addSubview:statusBarView];
    [self.tabBarController.tabBar setHidden:NO];
    
}
@end
